import api from '../../api/index';
import dayjs from '../../plugin/dayjs/index';
import daysbefore from '../../plugin/daysbefore';
import * as echarts from '../../components/ec-canvas/echarts';
import bleUtils from '../utils/bluetooth'
import Toast from '@vant/weapp/toast/toast';


//全局声明chart
var seriesDataArr = [];
var timeArr = [];
var chart = null;

// 时间格式化
function formatTime(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
}
function formatTime2(date = new Date()) {
	return dayjs(date).format('YYYY-MM-DD');
}
Component ({
	properties: {
	},
	/**
   * 页面的初始数据
   */
	data: {
		inputshow: false,
		inputlist: [
			{ unit: '步', value: '', text: '请输入心率' },
			{ unit: 'kcal', value: '', text: '请输入收缩压' },
			{ unit: 'kcal', value: '', text: '请输入舒张压' }
		],
		c_val: 80,
		shebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/xueya.png',
		fasleshebeiicon: 'https://hxhealth.oss-cn-beijing.aliyuncs.com/redstart/sportsAdministration/gantanhao.png',

		hartValue: '',
		upValue: '',
		downValue: '',
		linedata: null,
		show: false,
		ec: {
			// 初始化图表
			onInit: (canvas, width, height) => {
				//初始化echarts元素，绑定到全局变量，方便更改数据
				chart = echarts.init(canvas, null, {
					width: width,
					height: height
				});
				canvas.setChart(chart);
				return chart;
			}
		},
		bindDeviceId: null,
		gyValue: '--',
		dyValue: '--',
		pluseValue: '--',
		toast: null
	},

	/**
   * 生命周期函数--监听页面加载
   */
  ready: function() {
		// this.drawProgress()
		this.gethistrorylist(); //查看历史数据
		this.getloadlist(); //查询当前最新数据
		this.doInitBlue()
	},
	methods: {
			// 蓝牙初始化
			doInitBlue() {
				bleUtils.initBlueTooth().then((res) => {
				  this.doGetBluetoothAdapterState()
				})
			  },
			  // 获取蓝牙适配器状态
			  doGetBluetoothAdapterState() {
				bleUtils.getBluetoothAdapterState().then((res) => {
				})
			  },
			  //开始搜索蓝牙设备
			  doStartSearchBlueTooth() {
					const toast = Toast.loading({
						duration: 0, // 持续展示 toast
						forbidClick: true,
						message: '正在搜索蓝牙设备',
						zIndex: 100000,
						position: 'top',
						selector: '#custom-selector'
					});
					this.setData({
						toast: toast
					});
				bleUtils.startSearchBlueTooth().then((res) => {
				  console.log(res, '搜索设备成功')
						
				  this.doOnBluetoothDeviceFound()
				})
			  },
			  // 监听搜素到新的蓝牙设备
			  doOnBluetoothDeviceFound() {
					bleUtils.onBluetoothDeviceFound().then((res) => {
						this.setData({
						deviceList: res
						})
							const filterValue = res.filter(item => item.name === 'Belter_BT')
							if(filterValue.length > 0) {
								this.setData({
									bindDeviceId: filterValue[0].deviceId
								})
								this.data.toast.setData({
									message: `搜索到设备，正在链接设备`
								});
								// 搜索到可用的蓝牙设备，停止搜索
								bleUtils.stopSearchBlueTooth()
								this.bindEquipment()
							} else {
								//没有搜索到可用设备，重新搜索
								console.log('没有搜索到可用设备，重新搜索')
								// this.doStartSearchBlueTooth()
								this.setData({
									bindDeviceTextInfo: '没有搜索到对应的蓝牙设备，请重新搜索'
								})
								setTimeout(() => {
									this.setData({
										showDialog: false
									})
								}, 1500);
							}
					})
			  },
				// 连接蓝牙设备
			  bindEquipment() {
					this.data.toast.setData({
						message: `搜索到设备，正在链接设备`
					});
				bleUtils.createBLEConnection(this.data.bindDeviceId).then((res) => {
				  console.log(res, '连接成功')
						this.data.toast.setData({
							message: `链接设备成功，正在测量中`
						});
				  this.doGetBLEDeviceServices()
				}).catch(err => {
				  console.log(err, '连接设备失败')
				  this.doGetBLEDeviceServices()
				})
			  },
				// 获取蓝牙设备特征值
			  doGetBLEDeviceServices() {
				bleUtils.getBLEDeviceServices(this.data.bindDeviceId).then(res => {
						this.data.toast.setData({
							message: `测量结束`
						});
						setTimeout(() => {
							Toast.clear();
						}, 500);
						this.setData({
							gyValue: res.gy,
							dyValue: res.dy,
							pluseValue: res.pluse,
						})
						this.setData({
							'inputlist[0].value': res.gy
						});
						this.setData({
							'inputlist[1].value': res.dy
						});
						this.setData({
							'inputlist[2].value': res.pluse
						});
						this.savedevices()
					})
			  },
				gethistrorylist() {
					api
						.post('/api/hxhealth/exams/records', {
							data: {
								begindate: daysbefore.daysbefore(7),
								enddate: formatTime2(),
								everyday: true,
								itemcode: 'XYZBXY001003',
								typecode: 'bloodpmeter',
								everyday: true
							}
						})
						.then((res) => {
							// console.log(res);
							console.log('----历史数据----', res);
							if (res.length > 0) {
								const jsonData = res;
								// 提取数据的数组
								const values = [];
								const times = [];
			
								// 遍历 body 数组
								jsonData.forEach((entry) => {
									// 遍历 devices 数组
									entry.devices.forEach((device) => {
										console.log(device);
										// 找到 code 为 "XYZBXY001003" 的项
										const item = device.items.find((item) => item.code === 'XYZBXY001003');
			
										// 如果找到了，将 value 和 time 添加到相应的数组中
										if (item) {
											console.log(item);
											values.push(Number(item.value)); // 将值转换为数字类型
											times.push(entry.time.slice(0, 10).replace(/-/g, '/'));
										}
									});
								});
								const linedata = {
									values,
									times
								};
								console.log(linedata);
								this.setData({
									linedata
								});
								// 模拟获取接口数据
								setTimeout(() => {
									this.getEchartData(linedata);
								}, 1000);
							}
						});
				},
				getloadlist() {
					// 整体列表查询
					api
						.post('/api/exams/lastvalues', {
							data: {
								devkind: 'bloodpmeter',
								devmode: '',
								itemcode: '',
								typecode: '',
								unionuser: true
							}
						})
						.then((res) => {
							// console.log(res);
							console.log('----最新数据----', res);
							const array = res;
							for (let y = 0; y < array.length; y++) {
								if (array[y].code == 'XYZBXY001005') {
									this.setData({
										hartValue: array[y].value
									});
								}
								if (array[y].code == 'XYZBXY001003') {
									this.setData({
										upValue: array[y].value
									});
								}
								if (array[y].code == 'XYZBXY001002') {
									this.setData({
										downValue: array[y].value
									});
								}
							}
						});
				},
				savedevices() {
					console.log('2222');
					let data = {
						name: '血压监测',
						time: formatTime(),
						typecode: 'bloodpmeter',
						typename: '血压监测',
						devices: [
							{
								name: '血压监测',
								kind: 'bloodpmeter',
								items: [
									{
										code: 'XYZBXY001005',
										checkDate: null,
										level: null,
										value: this.data.inputlist[0].value,
										deviceBrand: '',
										deviceNo: ''
									},
									{
										code: 'XYZBXY001003',
										checkDate: null,
										level: null,
										value: this.data.inputlist[1].value,
										deviceBrand: '',
										deviceNo: ''
									},
									{
										code: 'XYZBXY001002',
										checkDate: null,
										level: null,
										value: this.data.inputlist[2].value,
										deviceBrand: '',
										deviceNo: ''
									}
								]
							}
						]
					};
					// 整体列表查询
					api
						.post('/api/hxhealth/exams/save', {
							data
						})
						.then((res) => {
							// console.log(res);
							console.log('----保存录入----', res);
							this.getloadlist();
							this.closesaveNickname();
							wx.showToast({
								icon: 'none',
								title: '保存成功'
							});
						})
						.catch((e) => {
							console.log(e);
							wx.showToast({
								icon: 'none',
								title: e.faultstring ? e.faultstring : '保存失败'
							});
						});
				},
				openNickname() {
					this.setData({
						inputshow: true
					});
				},
				closesaveNickname() {
					this.setData({
						inputshow: false
					});
				},
				userNameInput1(e) {
					console.log(e.detail.value);
					this.setData({
						'inputlist[0].value': e.detail.value
					});
				},
				userNameInput2(e) {
					console.log(e.detail.value);
					this.setData({
						'inputlist[1].value': e.detail.value
					});
				},
				userNameInput3(e) {
					console.log(e.detail.value);
					this.setData({
						'inputlist[2].value': e.detail.value
					});
				},
				saveNickname() {
					console.log(this.data.inputlist);
					this.savedevices();
				},
				modal_click_Hidden() {
					this.setData({
						inputshow: false
					});
				},
				// 绘制图表
				runColumncCanva() {
					var option = {
						title: {
							// text: '次/分',
							textStyle: {
								fontSize: 9,
								color: '#666666'
							}
						},
						color: [ '#37A2DA' ],
						legend: {
							data: [ '血压变化趋势' ],
							icon: 'circle',
							left: 0,
							itemWidth: 9
							// itemStyle: {
							//     color: '#5BBF70'
							// },
							// textStyle: {
							//     color: '#333333',
							//     fontSize: 13
							// }
						},
						grid: {
							left: '0%',
							right: '3%',
							bottom: 0,
							top: '15%',
							containLabel: true,
							show: true
						},
			
						tooltip: {
							show: true,
							trigger: 'axis'
						},
						xAxis: {
							type: 'category',
							boundaryGap: false,
							data: timeArr,
							axisLabel: {
								rotate: 45 //倾斜度 -90 至 90 默认为0
							}
						},
						yAxis: {
							type: 'value',
							splitLine: {
								lineStyle: {
									type: 'dashed'
								}
							}
						},
						series: seriesDataArr
					};
					//这里一定要做个charts是否存在的判断，因为万一ec那里没有初始化，这里就会报错
					if (chart) {
						chart.setOption(option);
						this.setData({
							show: true
						});
					}
				},
				getEchartData(linedata) {
					seriesDataArr = [
						{
							name: '血压变化趋势',
							type: 'line',
							stack: 'Total',
							smooth: true,
							data: linedata.values
						}
					];
					timeArr = linedata.times;
					this.runColumncCanva();
				},
				// 链接设备
				goBindEq() {
					this.doStartSearchBlueTooth()
				}
	},


	/**
   * 生命周期函数--监听页面初次渲染完成
   */
	onReady: function() {},

	/**
   * 生命周期函数--监听页面显示
   */
	onShow() {},

	/**
   * 生命周期函数--监听页面隐藏
   */
	onHide() {},

	/**
   * 生命周期函数--监听页面卸载
   */
	onUnload() {
		this.closeBLE(this.data.bindDeviceId)
	},

	/**
   * 页面相关事件处理函数--监听用户下拉动作
   */
	onPullDownRefresh() {},

	/**
   * 页面上拉触底事件的处理函数
   */
	onReachBottom() {},

	/**
   * 用户点击右上角分享
   */
	onShareAppMessage() {}
});
